from langchain.agents import AgentExecutor
from langchain.agents.format_scratchpad.openai_tools import format_to_openai_tool_messages
from langchain.agents.output_parsers.openai_tools import OpenAIToolsAgentOutputParser
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.tools.bearly.tool import BearlyInterpreterTool
from langchain.tools.ddg_search import DuckDuckGoSearchRun
from langchain.tools.render import format_tool_to_openai_tool

lc_tools = [DuckDuckGoSearchRun(), BearlyInterpreterTool(api_key="...").as_tool()]
oai_tools = [format_tool_to_openai_tool(tool) for tool in lc_tools]
prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a helpful assistant"),
        ("user", "{input}"),
        MessagesPlaceholder(variable_name="agent_scratchpad"),
    ]
)
llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo-1106")
agent = (
    {
        "input": lambda x: x["input"],
        "agent_scratchpad": lambda x: format_to_openai_tool_messages(
            x["intermediate_steps"]
        ),
    }
    | prompt
    | llm.bind(tools=oai_tools)
    | OpenAIToolsAgentOutputParser()
)
agent_executor = AgentExecutor(agent=agent, tools=lc_tools, verbose=True)
agent_executor.invoke(
    {"input": "What's the average of the temperatures in LA, NYC, and SF today?"}
)